package com.yunyouyi.cpicture.domain.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyouyi.cpicture.domain.user.entity.User;
import com.yunyouyi.cpicture.domain.user.repository.UserRepository;
import com.yunyouyi.cpicture.domain.user.service.UserDomainService;
import com.yunyouyi.cpicture.domain.user.valueobject.UserRoleEnum;
import com.yunyouyi.cpicture.infrastructure.exception.ErrorCode;
import com.yunyouyi.cpicture.infrastructure.exception.ThrowUtils;
import com.yunyouyi.cpicture.interfaces.dto.user.UserLoginDTO;
import com.yunyouyi.cpicture.interfaces.dto.user.UserQueryDTO;
import com.yunyouyi.cpicture.interfaces.dto.user.UserRegisterDTO;
import com.yunyouyi.cpicture.interfaces.vo.user.UserLoginVO;
import com.yunyouyi.cpicture.interfaces.vo.user.UserVO;
import com.yunyouyi.cpicture.shared.auth.StpKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.yunyouyi.cpicture.domain.user.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author yunyouyi
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-03-31 15:14:30
 */
@Service
@Slf4j
public class UserDomainServiceImpl implements UserDomainService {

    @Resource
    private UserRepository userRepository;
    /**
     * 用户注册
     * @param userRegisterDTO
     * @return
     */
    public long userRegister(UserRegisterDTO userRegisterDTO) {
        String userAccount = userRegisterDTO.getUserAccount();
        String userPassword = userRegisterDTO.getUserPassword();
        //检查账号是否与数据库重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count = userRepository.count(queryWrapper);
        ThrowUtils.throwIf(count > 0,ErrorCode.PARAMS_ERROR,"账号重复");
        //3.密码加密
        String encryptPassword = getEncryptPassword(userPassword);
        //4.插入数据到数据库
        User user = User.builder()
                .userAccount(userAccount)
                .userPassword(encryptPassword)
                .userName("momo")
                .userRole(UserRoleEnum.USER.getValue())
                .build();
        boolean result = userRepository.save(user);
        ThrowUtils.throwIf(!result,ErrorCode.SYSTEM_ERROR,"注册失败");
        return user.getId();
    }

    /**
     * 用户登录
     * @param userLoginDTO
     * @return 脱敏后的用户信息
     */
    public UserLoginVO userLogin(UserLoginDTO userLoginDTO, HttpServletRequest request) {
        String userAccount = userLoginDTO.getUserAccount();
        String userPassword = userLoginDTO.getUserPassword();
        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        User user = userRepository.getOne(queryWrapper);
        ThrowUtils.throwIf(user == null,ErrorCode.PARAMS_ERROR,"用户不存在或密码错误");
        //3.密码是否正确
        String encryptPassword = getEncryptPassword(userPassword);
        ThrowUtils.throwIf(!encryptPassword.equals(user.getUserPassword()),ErrorCode.PARAMS_ERROR,"用户不存在或密码错误");
        //4.保存用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE,user);
        //记录登录信息到Sa-token
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(USER_LOGIN_STATE,user);
        //5.脱敏
        log.info("user login information{}",user);
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user,userLoginVO);
        log.info("user login Anonymized information{}",userLoginVO);
        return userLoginVO;
    }

    /**
     * 获取当前登录用户
     * @param request
     * @return 当前登录用户
     */
    public User getLoginUser(HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        ThrowUtils.throwIf(currentUser == null || currentUser.getId() == null,ErrorCode.NOT_LOGIN_ERROR);
        //上面代码用户如果改信息，可能会出现不一致
        User user = userRepository.getById(currentUser.getId());
        ThrowUtils.throwIf(user == null,ErrorCode.NO_AUTH_ERROR);

        return currentUser;
    }

    /**
     * 获取当前登录用户（脱敏）
     * @param user
     * @return 当前登录用户（脱敏）
     */
    public UserLoginVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserLoginVO UserloginVO = new UserLoginVO();
        BeanUtils.copyProperties(user, UserloginVO);
        return UserloginVO;
    }


    /**
     * 获取脱敏用户
     * @param user
     * @return
     */
    public UserVO getUserVO(User user) {
        if(user == null){
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return userVO;
    }

    /**
     * 获取脱敏用户列表
     * @param userList
     * @return
     */
    public List<UserVO> getUserVOList(List<User> userList) {
        if(userList.isEmpty()){
            return new ArrayList<>();
        }
        return userList.stream()
                .map(this::getUserVO)
                .collect(Collectors.toList());
    }

    /**
     * 获取加密密码
     * @param userPassword
     * @return 加密后的密码
     */
    public String getEncryptPassword(String userPassword) {
        final String SALT = "yunyouyi";
        return DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
    }

    /**
     * 用户退出
     * @param request
     */
    public Boolean userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request.getSession().getAttribute(USER_LOGIN_STATE) == null,ErrorCode.NOT_LOGIN_ERROR);
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    /**
     * 处理用户信息
     * @param user
     * @return 脱敏后的用户信息
     */
    public UserLoginVO handleUser(User user){
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user,userLoginVO);
        return userLoginVO;
    }

    /**
     * 获取查询条件
     * @param userQueryDTO
     * @return
     */
    public QueryWrapper<User> getQueryWrapper(UserQueryDTO userQueryDTO) {
        ThrowUtils.throwIf(userQueryDTO == null,ErrorCode.PARAMS_ERROR);
        Long id = userQueryDTO.getId();
        String userName = userQueryDTO.getUserName();
        String userAccount = userQueryDTO.getUserAccount();
        String userProfile = userQueryDTO.getUserProfile();
        String userRole = userQueryDTO.getUserRole();
        String sortField = userQueryDTO.getSortField();
        String sortOrder = userQueryDTO.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id)
                .like(StrUtil.isNotBlank(userName), "userName", userName)
                .like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount)
                .like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile)
                .eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        return queryWrapper;
    }

    @Override
    public Boolean removeById(Long id) {
        return userRepository.removeById(id);
    }

    @Override
    public boolean updateById(User user) {
        return userRepository.updateById(user);
    }

    @Override
    public User getById(long id) {
        return userRepository.getById(id);
    }

    @Override
    public Page<User> page(Page<User> userPage, QueryWrapper<User> queryWrapper) {
        return userRepository.page(userPage, queryWrapper);
    }

    @Override
    public List<User> listByIds(Set<Long> userIdSet) {
        return userRepository.listByIds(userIdSet);
    }

    @Override
    public boolean saveUser(User userEntity) {
        return userRepository.save(userEntity);
    }
}




